package com.yadang.csv;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: 亚当
 * @date: 2023年05月16日 22:39
 * @package: com.yadang.csv
 * @Description: TODO
 */
public class TestCsv2 {
    public static void main(String[] args) {
        User user = new User();
        user.setUserName("张三");
        user.setSex("男");
        user.setAge(18);

        List<User> list = new LinkedList<User>();
        list.add(user);

        String csvFile = "D://users.csv";
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GBK"))) {
            // Write the CSV header
            writer.write("姓名,性别,年龄");
            writer.newLine();

            // Write the user data
            for (User u : list) {
                writer.write(u.getUserName() + "," + u.getSex() + "," + u.getAge());
                writer.newLine();
            }
            System.out.println("CSV file was created successfully !!!");

        } catch (IOException e) {
            System.out.println("Error writing to CSV file: " + e.getMessage());
        }

    }
}
